package com.ocom.payhandle.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.HttpUtils;
import com.ocom.common.dto.SubsidyDto;
import com.ocom.common.entity.card.EntityXfSignNo;
import com.ocom.common.entity.card.EntiyXfMerchPayInfo;
import com.ocom.common.entity.typehandler.SignNoHandle;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.payhandle.service.CcbMealAllowanceService;
import com.ocom.payhandle.service.SubsidyDataService;
import com.ocom.payhandle.service.XfMerchPayInfoService;
import com.ocom.payhandle.service.XfSignNoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class CcbMealAllowanceServiceImpl implements CcbMealAllowanceService {


    @Autowired
    private XfSignNoService xfSignNoService;

    @Autowired
    private SubsidyDataService subsidyDataService;

    @Autowired
    private XfMerchPayInfoService xfMerchPayInfoService;

    //余额查询
    private final static String API_URL_BALANCE = "http://192.168.3.123:32880/ocom_pay/ccb/wallet/balance.do";
    //虚拟账户钱包清零
    private final static String APL_URL_CLEARING = "http://192.168.3.123:32880/ocom_pay/ccb/wallet/clearing.do";
    //虚拟账户钱包充值
    public static final String APL_URL_RECHARGE = "http://192.168.3.123:32880/ocom_pay/ccb/wallet/recharge.do";

    @Override
    public Result grantSubsidy(SubsidyDto subsidyDto) {

        // 获取统一支付单位号
        EntiyXfMerchPayInfo xfMerchPayInfo = xfMerchPayInfoService.selectConfigure(subsidyDto.getComId(), 0l);
        if (xfMerchPayInfo == null) {
            return ResultUtil.error(ResultEnum.Err_1001);
        }

        // 用户签约号 查找签约信息
        EntityXfSignNo entityXfSignNo = xfSignNoService.getUserSignInfo(subsidyDto.getComId(), Long.valueOf(subsidyDto.getPId()), 0, 32, 1);
        if (entityXfSignNo == null) {
            return ResultUtil.error(ResultEnum.Err_1001);
        }

        SignNoHandle signNoHandle = new SignNoHandle();
        String signNo = signNoHandle.decrypt(entityXfSignNo.getSignNo(), entityXfSignNo.getComId());
        log.info("签约号:{}", signNo);

        // 余额查询
        Map<String, Object> map = new HashMap<>();
        map.put("pCode", signNo);
        //公共参数
        map.put("companyId", xfMerchPayInfo.getCompanyId());
        map.put("userName", xfMerchPayInfo.getUserName());
        map.put("payPassword", xfMerchPayInfo.getPassword());

        String postJson = HttpUtils.postJson(API_URL_BALANCE, map);
        JSONObject parsed = JSON.parseObject(postJson);

        if (parsed.getInteger("code") != 200) {
            log.info("余额查询结果：{}", parsed);
            return ResultUtil.error(ResultEnum.Err_1000);
        }

        JSONArray data = parsed.getJSONArray("data");

        if (ObjectUtil.isEmpty(data)) {
            return ResultUtil.error(ResultEnum.Err_1000);
        }

        data.forEach(dataItem -> {
            JSONArray accDataArray = ((JSONObject) dataItem).getJSONArray("ACC_DATA");
            for (Object accData : accDataArray) {
                JSONObject object = (JSONObject) accData;
                String accType = object.getString("ACC_TYPE");
                if (Long.parseLong(accType) != subsidyDto.getWallet() + 2) {
                    continue;
                }
                String accNo = object.getString("ACC_NO");
                String money = object.getString("MONEY");
                if (money.equals("0") || subsidyDto.getClearFlag() == 0) {
                    map.put("money", subsidyDto.getPlanMoney() / 100);
                    map.put("accNo", accNo);
                    map.put("orderId", subsidyDto.getOrderNo());
                    map.put("remark", subsidyDto.getRemark());
                    String postedJson = HttpUtils.postJson(APL_URL_RECHARGE, map);
                    JSONObject parsedObject = JSONObject.parseObject(postedJson);
                    log.info("虚拟账户钱包充值返回结果:{}", postedJson);
                    if (parsedObject.getInteger("code") != 200) {
                        continue;
                    }
                } else {
                    map.put("accNo", accNo);
                    map.put("orderId", "QL" + subsidyDto.getOrderNo());
                    map.put("remark", subsidyDto.getRemark());
                    String result = HttpUtils.postJson(APL_URL_CLEARING, map);
                    log.info("虚拟账户钱包清零返回结果:{}", result);
                    JSONObject parseObject = JSONObject.parseObject(result);
                    if (parseObject.getInteger("code") != 200) {
                        continue;
                    }
                }
                double amout = Double.parseDouble(money);
                amout=-amout;
                String negativeMoney=String.valueOf(amout);
                subsidyDataService.updateSubsidyData(subsidyDto.getComId(), subsidyDto, xfMerchPayInfo.getCompanyId(), negativeMoney);
            }
        });
        return ResultUtil.success();
    }
}
